<template>
    <div class="app-container">
      <div class="search-bar">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="auto">
          <el-row>
              <el-form-item>
                <el-button type="primary" icon="search" @click="handleQuery()">搜索</el-button>
                <el-button icon="refresh" @click="handleResetQuery()">重置</el-button>
              </el-form-item>
          </el-row>
        </el-form>
      </div>
      <el-card shadow="never">
        <el-button type="primary" style="margin-bottom: 10px;" @click="handleDelete({})">
            批量删除
        </el-button>
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" min-width="100">
            <template #default="{$index}">
              {{ (paging.page - 1) * paging.size + $index + 1 }}
            </template>
          </el-table-column>
          
          <el-table-column label="文件名" prop="filename" min-width="100">
            <template #default="scope">
              {{ decodeURIComponent(scope.row.filename) }}
            </template>
          </el-table-column>
          <el-table-column label="导出数量" prop="exported" min-width="100"></el-table-column>
          <el-table-column label="导出时间" prop="createdAt" min-width="160">
            <template #default="scope">
              {{ scope.row.createdAt ? formatDate(scope.row.createdAt) : '--'}}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right">
            <template #default="scope">
              <el-dropdown @command="handleClickBatch($event, 'Row', scope.row)">
                <span class="el-dropdown-link">
                  操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="export">导出</el-dropdown-item>
                    <el-dropdown-item command="delete">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
  
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            v-model:current-page="paging.page"
            v-model:page-size="paging.size"
            :page-sizes="['10', '20', '30', '50', '100']"
            :size="paging.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="paging.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </template>
  
  
  <script setup>
  import { getExportList, exportDel, exportAgain } from "@/api/equipmentManagement/derivedRecord.api";
  import useToggle from "@/hooks/useToggle";
  import { formatDate } from "@/utils";
  import { downloadZipFile } from '@/utils/index'
  import { ElLoading } from 'element-plus'

  const [loading, _, setLoading] = useToggle();

  const props = defineProps({
    appType: {
      type: String,
      required: false,
      default: 'WA'
    }
  })
  
  const queryParams = ref({
    app: props.appType,
  })
  
  const paging = ref({
    size: 10,
    page: 1,
    total: 0,
  });
  
  const tableData = ref([]);
  
  const handleSizeChange = (e) => {
    paging.value.size = e;
    getList()
  };
  const handleCurrentChange = (e) => {
    paging.value.page = e;
    getList()
  };
  
  const ids = ref([]);
  const handleSelectionChange = (e) => {
    ids.value = e.map((item) => item.id);
  }
  
  const getList = async () => {
    try {
      setLoading(true);
      const res = await getExportList({
        ...queryParams.value,
        page: paging.value.page,
        size: paging.value.size,
      })
      paging.value.total = res.count;
      tableData.value = res.results;
      setLoading(false);
    } finally {
      setLoading(false);
    }
  }
  
  const handleQuery = () => {
    getList()
  };
  
  handleQuery()
  
  const handleResetQuery = () => {
    if (!queryFormRef.value) return
    queryFormRef.value.resetFields()
  }
  
  const handleClickBatch = (command, type, row) => {
    const commands = {
      export: () => handleExport(row),
      delete: () => handleDelete(row),
    }[`${command}`]
  
    return commands && commands();
  }
  const handleExport = (row) => {
    const config = {}
    if(props.appType === 'TG') config.responseType = 'blob'
    const loadingDownload = ElLoading.service({
      lock: true,
      text: '正在下载中，请稍后...',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    exportAgain({ id: row.id, app:'TG' }, config).then((res) => {

      if(props.appType == "TG") {
        const fileName = res.headers["content-disposition"] && res.headers["content-disposition"].split("=")[1];
        downloadZipFile(res.data, decodeURIComponent(fileName?.split("''")[1]) || 'default.tar')
        return
      }
      
      const decoder = new TextDecoder('utf-8');
      const buffer = new Uint8Array(res.data).buffer;
      const str = decoder.decode(buffer);
      const blob = new Blob([str], { type: 'application/octet-stream' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = res.fileName || 'default.txt';
      link.click();
      URL.revokeObjectURL(url);
      return
    }).finally(() => {
      loadingDownload.close()
    })
  }
  const handleDelete = (row) => {
    if(!row.id && ids.value.length === 0) return ElMessage.warning('请选择要删除的记录');
    const tips = `确定删除${!row.id ? `${ids.value.length}条记录` : '这条记录'}?`;
  
    ElMessageBox.confirm(
      tips,
      '温馨提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        del()
      })
  
  
      const del = async() => {
        if(row.id) {
          const res =await exportDel({ ids: [Number(row.id)] })
          console.log(res);
          if(res) {
            ElMessage.success('删除成功');
            handleQuery();
          }
          return
        }
  
        const res =await exportDel({ ids: ids.value })
        if(res) {
          ElMessage.success('删除成功');
          handleQuery();
        }
      }
  };
  </script>
  
  <style scoped lang="scss">
  .pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 15px;
  }
  </style>
  